/*
 * Copyright 2016-2021 Pnoker. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.rundow.common.sdk.init;


import com.rundow.common.sdk.bean.driver.ServiceContainerContext;
import com.rundow.common.sdk.service.DriverMetadataService;
import com.rundow.common.sdk.service.DriverScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Driver SDK Initial
 *
 * @author pnoker
 */
@Slf4j
@Component

public class DriverInitRunner implements ApplicationRunner {


    @Resource
    private DriverMetadataService driverMetadataService;

    @Resource
    private ServiceContainerContext serviceContainerContext;


    @Override
    public void run(ApplicationArguments args) throws Exception {
//
//        log.info("Driver  Init ……");
//        // Initialize driver configuration
//        driverMetadataService.initial();
//
//        // Initialize custom driver service
//        driverInitial();
//
//        // Initialize driver schedule service
//        scheduleInitial();
    }


    private void driverInitial() {
        log.info("serviceContainerContext={}",serviceContainerContext);
        serviceContainerContext.values().stream().forEach( serviceContainer -> {
            serviceContainer.getCustomService().initial();
        });
    }



    private void scheduleInitial() {
        serviceContainerContext.entrySet().stream().forEach((Map.Entry<String, ServiceContainerContext.ServiceContainer> entry)->{
            final String driverName = entry.getKey();
            final ServiceContainerContext.ServiceContainer serviceContainer = entry.getValue();
            final DriverScheduleService scheduleService = serviceContainer.getScheduleService();
            try {
                // 间隔一段时间去注册不同的sehedule
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            scheduleService.initial(driverName);
        });
    }



}
